package com.ceba.test.base.utils;

import abc.docs.Document;
import abc.util.DateUtils;
import abc.util.FileHelper;
import abc.util.RARUtils;
import abc.util.ZipUtils;
import com.ceba.base.helper.LoggerHelper;
import com.ceba.base.utils.IDSFileUtils;
import com.ceba.base.utils.ToPdfUtils;
import com.ceba.cebautils.DateUtil;
import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.configs.CebaPathUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;

@SuppressWarnings("deprecation")
public class CebaFileManageUtil {

	private static Logger logger = LoggerFactory.getLogger(CebaFileManageUtil.class);

	/**
	 * 过滤文件名特殊字符
	 * @param fileName
	 * @return
	 */
	public static String filterFileName(String fileName) throws Exception {
//		 String ext =FileUtil.getFileExtName(fileName);
//		 if(ext!=null){
//			 fileName= StringUtil.indexRepxStr(fileName.substring(0, fileName.lastIndexOf(".")), "[\u4e00-\u9fa5a-zA-Z0-9]")+"."+ext;
//		 }else{
//			 fileName= StringUtil.indexRepxStr(fileName, "[\u4e00-\u9fa5a-zA-Z0-9]");
//		 }

//		return fileName.replace("}", "").replace("{", "").replace("[", "").replace("]", "").replace("/", "").replace("\\", "").replace("|", "");
		return fileName.replace("/", "").replace("\\", "").replace("|", "");
	}

	/**
	 * 过滤文件名特殊字符
	 * @param fileName
	 * @return
	 */
	public  static String filterFolderName(String folderName) throws Exception{
//		folderName= StringUtil.indexRepxStr(folderName.substring(0, folderName.lastIndexOf(".")), "[\u4e00-\u9fa5a-zA-Z0-9]");
//		return folderName.replace("}", "").replace("{", "").replace("[", "").replace("]", "").replace("/", "").replace("\\", "").replace("|", "").replace(".", "");
		return folderName.replace("/", "").replace("\\", "").replace("|", "").replace(".", "");
	}
	
	/**
	 * 过滤文件夹名特殊字符
	 * @return
	 */
	public static String filterJsonName(String jsonName) throws Exception{
//		jsonName= StringUtil.indexRepxStr(jsonName.substring(0, jsonName.lastIndexOf(".")), "[\u4e00-\u9fa5a-zA-Z0-9]");
		return jsonName.replace("}", "").replace("{", "").replace("[", "").replace("]", "").replace("\\", "");
	}
	
	/**
	 * 根据拓展名获取文件图标类型
	 * 
	 * @param extensions
	 *            拓展名类型
	 * @return
	 */
	public static  String getFileExtensionsImg(String extensions) {
		String img = "";
		try {
			extensions = extensions.toLowerCase();
			String relativePath = "../../../../libs/ids/filemanager/";
			if ("acc".equals(extensions) || "avi".equals(extensions) || "bmp".equals(extensions) || "chm".equals(extensions)
					|| "css".equals(extensions) || "dll".equals(extensions) || "doc".equals(extensions)
					|| "docx".equals(extensions) || "fla".equals(extensions) || "gif".equals(extensions)
					|| "htm".equals(extensions) || "html".equals(extensions) || "ini".equals(extensions)
					|| "jar".equals(extensions) || "jpeg".equals(extensions) || "jpg".equals(extensions)
					|| "js".equals(extensions) || "lasso".equals(extensions) || "mdb".equals(extensions)
					|| "mov".equals(extensions) || "mp3".equals(extensions) || "mp4".equals(extensions)
					|| "mpg".equals(extensions) || "ogg".equals(extensions) || "ogv".equals(extensions)
					|| "pdf".equals(extensions) || "php".equals(extensions) || "png".equals(extensions)
					|| "ppt".equals(extensions) || "py".equals(extensions) || "rb".equals(extensions)
					|| "real".equals(extensions) || "reg".equals(extensions) || "rtf".equals(extensions)
					|| "sql".equals(extensions) || "swf".equals(extensions) || "txt".equals(extensions)
					|| "vbs".equals(extensions) || "wav".equals(extensions) || "webm".equals(extensions)
					|| "wma".equals(extensions) || "wmv".equals(extensions) || "xls".equals(extensions)
					|| "xlsx".equals(extensions) || "xml".equals(extensions) || "xsl".equals(extensions)
					|| "zip".equals(extensions) ) {
				img = "images/fileicons2/" + extensions + ".png";
			} else if ("rar".equals(extensions)) {
				img = "images/fileicons2/zip.png";
			} else if ("locked__open".equals(extensions)) {
				img = "images/fileicons2/locked__Open.png";
			} else if ("_net".equals(extensions)) {
				img = "images/fileicons2/_Net.png";
			} else if ("dir".equals(extensions)) {
				img = "images/fileicons2/_Open.png";
			} else if ("otherImage".equals(extensions)) {
				img = "images/fileicons2/other_image.png";
			} else if ("dot".equals(extensions) || "dotx".equals(extensions)) {
				img = "images/fileicons2/dot.png";
			} else if ("sign".equals(extensions)) {
				img = "images/fileicons2/pdfsign.png";
			} else if ("pptx".equals(extensions)) {
				img = "images/fileicons2/pptx.png";
			} else {
				img = "images/fileicons2/default.png";
			}
			img = relativePath + img;
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return img;
	}
	/**
	 * 获取FM的父级路径
	 * @param fmPath 要拷贝目录ID
	 * @return
	 * @throws Exception
	 */
	public static String getFmParentPath(String fmPath) throws Exception{

		if (fmPath != null && !fmPath.equals("")) {
			//如果不是文件，则把最后一个/换成，再处理
			if(!fmPath.contains(".")){
				fmPath=fmPath.substring(0,fmPath.length()-1)+".a";
			}
			String[] arr=fmPath.split("/");
			String fmParentPath="/";
			for (String name : arr) {
				if (!name.equals("") && !name.contains(".")) {
					fmParentPath+=name+"/";
				}
			}
			return fmParentPath;
		}
			
		return "";
	}

	
	public static  String sortJSON2String(JSONObject json) {
		StringBuilder buffer = new StringBuilder();
		try {
			if (json.length() <= 0) {
				return "{}";
			}
			List<JSONObject> list = new ArrayList<JSONObject>();
			Iterator<String> iterator = json.keys();
			while (iterator.hasNext()) {
				String key = iterator.next();
				JSONObject jsonObject = json.getJSONObject(key);
				list.add(jsonObject);
			}
			Collections.sort(list, new Comparator<JSONObject>() {
				@Override
				public int compare(JSONObject o1, JSONObject o2) {
					return o1.getInt("Index") - o2.getInt("Index");
				}
			});
			/* 1.8 
			list.sort(new Comparator<JSONObject>() {
				@Override
				public int compare(JSONObject o1, JSONObject o2) {
					return o1.getInt("Index") - o2.getInt("Index");
				}
			});*/
			buffer.append("{");
//			for (JSONObject jsonObject : list) {
			for (int i = 0; i < list.size(); i++) {
				
//				buffer.append("\"/" + jsonObject.getString("Path").replace(jsonObject.getString("ID") + "/", "") + "\":");
				buffer.append("\"/" + i + "\":");
				// jsonObject.remove("Index");
				buffer.append(list.get(i).toString());
				buffer.append(",");
			}
			buffer.append("*}");
			String stringJson = buffer.toString();
			return stringJson.replace(",*}", "}");
		} catch (JSONException e) {
			LoggerHelper.error(logger, e, "");
			return "{}";
		}
	}

	
	/**
	 * 获取文件内容
	 * @param path 文件路径
	 * @return
	 */
	public static String getFileContent(String path){
		String text="";
		try {
			File file = new File(path);
			String extName=FileHelper.getFileExtName(path).toLowerCase();
			if(extName.equals("txt")){
				text = FileHelper.getFileContent(file, "gbk");
			}else if(extName.equals("doc") || extName.equals("docx")|| extName.equals("xls") || extName.equals("xlsx")){
				text = Document.getDocumentText(path, true);
			}else if(extName.equals("pdf")){
				text = ToPdfUtils.getDocumentText(path);
			}
			
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			text = "";
		}
		
		return text;
	}



	
	
	
	/**
	 * 把压缩包解压某个文件夹中
	 * 
	 * @param zipPath
	 *            压缩包路径
	 * @param toFolderPath
	 *            解压到路径
	 * @return 如果返回有路径，则说明解压成功，无则说明解压有问题；
	 * @throws Exception
	 */
	public static String unZipTo(String zipPath, String toFolderPath)  {
		File dir = new File(toFolderPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		if (FileHelper.exists(zipPath)) {
			String extName = FileHelper.getFileExtName(zipPath);
			String pass = DateUtil.getYearAndMonth(DateUtil.YYYYMM, 0)+"ABC";
			if (extName.toLowerCase().equals("zip")) {
				try {
					//每次数据库升级时，先密码压缩成zip文件，密码规则为年月ABC如201606ABC
					//unzip时计算密码，根据日期自行计算
					ZipUtils.unzip(zipPath, toFolderPath);
//					ZipUtils.unzip(zipPath, toFolderPath,pass);
					Collection<File> files = FileHelper.listFiles(toFolderPath);
					if(files != null  && !files.isEmpty()){
						return toFolderPath;
					}
				} catch (Exception e) {
					LoggerHelper.error(logger, e, "");
					RARUtils.unzip(zipPath, toFolderPath);
					return toFolderPath;
				}
				
			} else if (extName.toLowerCase().equals("rar")) {
				try {
					RARUtils.unzip(zipPath, toFolderPath);
					return toFolderPath;
				} catch (Exception e) {
					LoggerHelper.error(logger, e, "");
					try {
						ZipUtils.unzip(zipPath, toFolderPath,pass);
						Collection<File> files = FileHelper.listFiles(toFolderPath);
						if(files != null  && !files.isEmpty()){
							return toFolderPath;
						}
					} catch (Exception e1) {
						LoggerHelper.error(logger, e1, "");
					}
				}
				
			}

		}

		return "";
	}




	
	public static Boolean isFile(String path) throws Exception {
		File file = new File(path);
		if (file.isFile()) {
			return true;
		}

		return false;
	}

	public Boolean isDirectory(String path) throws Exception {
		File file = new File(path);
		if (file.isDirectory()) {
			return true;
		}
		return false;
	}

	/**
	 * 如果目录不存在则创建目录
	 * 
	 * @param path
	 *            目录路径
	 * @return
	 * @throws Exception
	 */
	public static Boolean nullToCreateDirectory(String path) throws Exception {
		File dir = new File(path);
		if (!dir.exists()) {
			if (dir.mkdirs()) {
				return true;
			} else {
				return false;
			}

		}
		return true;
	}

	/**
	 * 如果文件的父级路径不存在，则创建相应目录
	 * 
	 * @param path
	 *            文件路径
	 * @return
	 * @throws Exception
	 */
	public static Boolean createDirectory(String path) throws Exception{
		File file = new File(path);
		File parent = file.getParentFile();
		if (parent != null && !parent.exists()) {
			if (parent.mkdirs()) {
				return true;
			} else {
				return false;
			}
		}
		return true;
	}

	/**
	 * 文件重命名
	 * 
	 * @param path
	 *            原始文件路径
	 * @param newName
	 *            新文件名，必须带有拓展名
	 * @return 如果返回路径说明成功，如果没有返回空，说明更名失败
	 * @throws Exception
	 */
	public String updateFileName(String path, String newName) throws Exception {

		File file = new File(path);
		if (file.isFile()) {
			String newPathName = file.getAbsolutePath() + "//" + newName;
			if (file.renameTo(new File(newPathName))) {
				return newPathName;
			}
		}
		return "";
	}

	/**
	 * 文件覆盖
	 * 
	 * @param path
	 *            原始文件路径
	 * @param toPath
	 *            需要覆盖的文件路径
	 * @return
	 * @throws Exception
	 */
	public static  Boolean cover(String path, String toPath) throws Exception {

		File file = new File(path);
		File toFile = new File(toPath);
		if (file.isFile()) {
			if (toFile.isFile()) {
				// 如果文件不相同
				if (file.length() != toFile.length()) {
					FileHelper.copyFile(path, toPath);
				}
			}
		}
		return false;
	}
}
